import 'dart:async';

import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/main/home/ab_home_page.dart';
import 'package:ceramics/pages/main/hot/ab_hot_page.dart';
import 'package:ceramics/pages/main/mine/ab_mine_page.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/util/ab_log.dart';
import 'package:ceramics/util/image_multi_selection_widget.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';


class ABPublishPage extends StatefulWidget {
  const ABPublishPage({super.key});

  @override
  State<ABPublishPage> createState() => _ABPublishPageState();
}

class _ABPublishPageState extends State<ABPublishPage> {

  final _contentController = TextEditingController();
  final _titleController = TextEditingController();
  final _imageMultiSelectionController = ImageMultiSelectionController();

  @override
  void initState() {
    super.initState();
    _fetchUserPolicy();
  }

  _fetchUserPolicy() async {
    await api.fetchUserPolicy();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        leading: const BackButton(color: Colors.black),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage("images/login_bg.webp"),
              fit: BoxFit.cover,
            ),
          ),
          height: double.infinity,
          child: SingleChildScrollView(
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            child: Column(
              children: [
                20.toVerticalBox,
                ImageMultiSelectionWidget(
                    controller: _imageMultiSelectionController,
                    addWidget: Container(
                    color: const Color(0xFFF6f6f6),
                    child: Image.asset('images/add.png',scale: 3))),
                TextField(
                  controller: _titleController,
                  decoration: const InputDecoration(
                    hintText: "Please input your title",
                    hintStyle: TextStyle(color: Colors.grey),
                    border: UnderlineInputBorder(borderSide: BorderSide(color: ABStyles.normalBlack)),
                  ),
                ),
                20.toVerticalBox,
                TextField(
                  controller: _contentController,
                  decoration: InputDecoration(
                    hintText: "Please input your content",
                    hintStyle: const TextStyle(color: Colors.grey),
                    border: OutlineInputBorder(
                      borderSide: const BorderSide(color: ABStyles.normalBlack),
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  maxLines: 10,
                  maxLength: 500,
                ),
                20.toVerticalBox,
                ABElevateButton(
                  onPressed: _add,
                  child: const Text("Apply To Add",style: ABStyles.tsWhite20R),
                ).size(width: 300,height: 44),
              ],
            ).padSymmetric(horizontal: 20),
          ),
        ),
      )
    );
  }
  
  

  void _add() async {
    if (_imageMultiSelectionController.images.isEmpty) {
      toast("Please select at least one image");
      return;
    }
    if (_contentController.text.isEmpty) {
      toast("Please input content");
      return;
    }
    loading(msg:'uploading image...');
    var res = await api.uploadImages(_imageMultiSelectionController.images);
    var images = res.map((e) => e.filename ?? '').toList();
    loading(msg:'uploading works...');
    var id = await ABWorks.insertMyWorks(images: images, title: _titleController.text, detail: _contentController.text);
    Log.i(id);
    dismissLoading();
    toast("Post success");
    Get.find<ABHomeController>().loadData();
    Get.find<ABHotController>().loadData();
    Get.find<ABMineController>().fetchMyWorks();
    Get.back();
  }
}
